package com.mach.platform.sprider.dev;

import com.mach.platform.sprider.Conf;
import com.mach.platform.util.SqlHelper;
import org.joda.time.DateTime;

import java.io.IOException;

/*
    取得变频器数据抓取器,一个对象针对一个采集模块
 */
public abstract class TransducerPlDev extends DataHelper {

    protected String devName;

    protected SqlHelper sqls;

    protected TransducerPlDev(String ip, Integer port, Integer devID, String devName) {
        super(ip,port,devID);

        this.sqls  = Conf.getSqlHelper();

        this.devName = devName;
    }

    @Override
    public void run(){

        long preSec = 0;
        long nowSec = 0;
        while(true){


            try {

//                long nowMill = System.currentTimeMillis();
//
//                nowSec = nowMill / 1000;
//
//                if(nowSec == preSec)continue;
//
//                Date now = new Date(nowMill);
//
//                int fyear = now.getYear() + 1900;
//                int fmonth = now.getMonth() + 1;
//                int fday = now.getDate();
//                int fhour = now.getHours();
//                int fmin = now.getMinutes();
//                int fsec = now.getSeconds();

                DateTime dateTime = new DateTime();
                int fyear = dateTime.getYear();
                int fmonth = dateTime.getMonthOfYear();
                int fday = dateTime.getDayOfMonth();
                int fhour = dateTime.getHourOfDay();
                int fmin = dateTime.getMinuteOfHour();
                int fsec = dateTime.getSecondOfMinute();

                Float pl =  this.getPl();


                this.sqls.updateAsync("insert ignore into data_detail(dev_id, fyear, fmonth, fday, fhour, fmin, fsec,fdatetime, " +
                        "pl) value" +
                        "('"+this.devName+"',"+fyear+","+fmonth+","+fday+","+fhour+","+fmin+","+fsec+","+"date_format(concat("+fyear+",'-',"+fmonth+",'-',"+fday+",' ',"+fhour+",':',"+fmin+",':',"+fsec+")," +
                        "'%Y-%m-%d %H:%i:%s'),"
                        +pl+")");

                this.sqls.updateAsync("replace into data_cur (dev_id,pl,update_time) value " +
                        "( " +
                        "'"+this.devName+"',"+
                        pl + "," +
                        "date_format(concat("+fyear+",'-',"+fmonth+",'-',"+fday+",' ',"+fhour+",':',"+fmin+",':',"+fsec+")," +
                                "'%Y-%m-%d %H:%i:%s')" +
                        ")");

//                Thread.sleep(1000*60);

            } catch (Exception e) {
                e.printStackTrace();
            }

            preSec = nowSec;


        }


    }

    /*
      取变频器状态, Null则为无数据,0则为异常,1为正常
   */
    public abstract Float getPl();


    public static void main(String[] args) throws IOException {
        TransducerPlDev td = new TransducerPlSNDDev("192.168.3.91",8000,4,"8#变频器（PA2工艺16H）");
        Float pl = td.getPl();
        System.out.println("pl="+pl);
    }


}
